<template>
    <div class="income-trend-panel">
        <!-- 顶部筛选 -->
        <div class="filter-bar">
            <div style="width: 360px">
                <el-date-picker v-model="dateRange" :disabled-date="disabledDate" type="daterange" range-separator="-" start-placeholder="开始日期"
                    end-placeholder="结束日期" style="margin-right: 12px;" size="small" value-format="YYYY-MM-DD"/>
            </div>
            <el-button-group style="margin-right: 12px;">
                <el-button :type="quickType==='7' ? 'primary' : 'default'" size="small"
                    @click="setQuick('7')">近7天</el-button>
                <el-button :type="quickType==='30' ? 'primary' : 'default'" size="small"
                    @click="setQuick('30')">近30天</el-button>
            </el-button-group>
            <el-button type="primary" size="small" @click="handleQuery">查询</el-button>
        </div>
        <!-- 收益趋势图 -->
        <div ref="trendChartRef" class="trend-chart"></div>
        <!-- 收益明细表 -->
        <el-table :data="tableData" border style="width:100%;margin-top:24px;">
            <el-table-column prop="timeId" label="日期" min-width="120" />
            <el-table-column prop="settleBw" label="结算带宽/Gbps" min-width="120" />
            <el-table-column prop="realIncome" min-width="140">
                <template #header>
                    实际结算收益/元
                    <el-tooltip content="实际结算收益说明" placement="top">
                        <i class="el-icon-question"></i>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="contributeIncome" label="贡献收益/元" min-width="120" />
            <el-table-column prop="deductCash" label="SLA扣减/元" min-width="120" />
            <el-table-column prop="otherIncome" label="其他收益/元" min-width="120" />
        </el-table>
    </div>
</template>
  
  <script setup name="IncomeTrendPanel">
  import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
  import * as echarts from 'echarts'
  import { incomeTrend } from '@/api/producer/device'
  
  const { proxy } = getCurrentInstance()
  const dateRange = ref([])
  const quickType = ref('')
  const createTime = ref('') 
  const setQuick = (type) => {
    quickType.value = type
    if (type === '7') {
      const [begin, end] = getRecentRange(7)
      dateRange.value = [begin, end]
    } else if (type === '30') {
      const [begin, end] = getRecentRange(30)
      dateRange.value = [begin, end]
    } else {
      dateRange.value = []
    }
  }
  
  const trendChartRef = ref(null)
  let trendChartInstance = null
  
  const chartDates = ref([])
  const chartValues = ref([])
  
  const trendOption = {
    grid: { left: 60, right: 40, top: 40, bottom: 40 },
    tooltip: { 
      trigger: 'axis',
      formatter: function(params) {
        const data = params[0]
        return `${data.name}<br/>收益: ${data.value} 元`
      }
    },
    xAxis: {
      type: 'category',
      data: chartDates.value,
      axisLabel: { color: '#888' },
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      min: 0,
      splitLine: { lineStyle: { color: '#eee' } },
      axisLabel: { 
        color: '#888',
        formatter: function(value) {
          return value.toFixed(2)
        }
      },
      name: '收益金额(元)',
      nameTextStyle: { align: 'center', padding: [0, 0, 0, 0] }
    },
    series: [
      {
        name: '实际收益',
        data: chartValues.value,
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: { color: '#5B8FF9', width: 2 },
        itemStyle: { color: '#5B8FF9', borderColor: '#fff', borderWidth: 2 }
      }
    ]
  }
  
  const tableData = ref([])
  
  function initTrendChart() {
    if (trendChartRef.value) {
      trendChartInstance = echarts.init(trendChartRef.value)
      // 初始化时不设置数据，等数据加载后再设置
      window.addEventListener('resize', resizeTrendChart)
    }
  }
  function disposeTrendChart() {
    window.removeEventListener('resize', resizeTrendChart)
    if (trendChartInstance) {
      trendChartInstance.dispose()
      trendChartInstance = null
    }
  }
  function resizeTrendChart() {
    trendChartInstance && trendChartInstance.resize()
  }
  
  onMounted(() => {
    nextTick(() => {
      initTrendChart()
      createTime.value = props.formDrawer.createTime
    })
  })
  onBeforeUnmount(() => {
    disposeTrendChart()
  })
  
  const props = defineProps({
    formDrawer: {
      type: Object,
      required: true
    },
    activeName: { type: String, required: true }
  })

  // 盒子创建时间
  function disabledDate(date) {
    if (!createTime.value) return false; // 没有 createTime 不禁用
    // 只比较年月日，忽略时分秒
    const create = new Date(createTime.value);
    create.setHours(0, 0, 0, 0);
    const d = new Date(date);
    d.setHours(0, 0, 0, 0);
    return d < create;
  }
  
  function renderChart() {
    if (!trendChartInstance && trendChartRef.value) {
      trendChartInstance = echarts.init(trendChartRef.value)
    }
    if (trendChartInstance) {
      // 计算Y轴最大值，确保数据能完整显示
      const maxValue = Math.max(...chartValues.value, 0)
      const yAxisMax = maxValue > 0 ? maxValue * 1.2 : 100 // 给20%的余量
      
      trendChartInstance.setOption({
        tooltip: { 
          trigger: 'axis',
          formatter: function(params) {
            const data = params[0]
            return `${data.name}<br/>收益: ${data.value} 元`
          }
        },
        xAxis: {
          type: 'category',
          data: chartDates.value,
          boundaryGap: false,
          axisLabel: { color: '#888' }
        },
        yAxis: {
          type: 'value',
          name: '收益金额(元)',
          min: 0,
          max: yAxisMax,
          splitLine: { lineStyle: { color: '#eee' } },
          axisLabel: { 
            color: '#888',
            formatter: function(value) {
              return value.toFixed(2)
            }
          },
          nameTextStyle: { align: 'center', padding: [0, 0, 0, 0] }
        },
        series: [
          {
            name: '实际收益',
            type: 'line',
            data: chartValues.value,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: { color: '#5B8FF9', width: 2 },
            itemStyle: { color: '#5B8FF9', borderColor: '#fff', borderWidth: 2 }
          }
        ]
      })
    }
  }
  
/**
 * 查询收益趋势
 * **/
async function fetchIncomeTrend(sn, range = []) {
    if (!sn) return
    let params = { sn }

    const res = await incomeTrend(proxy.addDateRange(params, dateRange.value))
    if (res && res.data && res.data.length > 0) {
        chartValues.value = res.data.map(row => Number(row.realIncome) || 0)
        chartDates.value = res.data.map(row => row.timeId || '')
        tableData.value = res.data
        
        // 确保图表已初始化后再渲染
        nextTick(() => {
          renderChart()
        })

        // 设置默认 dateRange（只在未手动选区间时）
        if (!dateRange.value.length) {
            const dates = res.data.map(row => row.timeId).filter(Boolean)
            if (dates.length) {
                // 假设日期已排序，否则排序
                const sorted = [...dates].sort()
                dateRange.value = [sorted[0], sorted[sorted.length - 1]]
            }
        }
    } else {
        // 没有数据时清空图表
        chartValues.value = []
        chartDates.value = []
        tableData.value = []
        if (trendChartInstance) {
          trendChartInstance.clear()
        }
    }
}

/***
 * 获取近7天、30天的日期范围
 */
 function getRecentRange(days) {
  const end = new Date()
  const start = new Date()
  start.setDate(end.getDate() - days + 1)
  // 格式化为 yyyy-MM-dd
  const format = d => d.toISOString().slice(0, 10)
  console.log(format(start), format(end), '时间')
  return [format(start), format(end)]
}

/**
 *日期通用格式化
 * **/
 function formatDateToYMD(date) {
  if (!(date instanceof Date)) {
    date = new Date(date)
  }
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}
  
watch(
  [() => props.activeName, () => props.formDrawer.sn],
  ([tab, sn], [oldTab, oldSn]) => {
    if (tab === 'first' && sn) {
      fetchIncomeTrend(sn, dateRange.value)
    }
  },
  { immediate: true }
)

function handleQuery() {
  fetchIncomeTrend(props.formDrawer.sn, dateRange.value)
}
  </script>
  
  <style scoped>
  .income-trend-panel {
    background: #fff;
    padding: 0;
  }
  .filter-bar {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    margin-top: 8px;
  }
  .trend-chart {
    width: 100%;
    height: 300px;
    margin-bottom: 0;
    min-height: 300px;
  }
  </style>